package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.ConstConstants;
import com.itheima.reggie.common.R;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        boolean match = check(requestURI);
        if(match){
            filterChain.doFilter(request,response);
            return;
        }
        //网页端的登录验证
        if(request.getSession().getAttribute(ConstConstants.EMPLOYEE_ID_IN_SESSION)!=null){
           Long empId=(Long)request.getSession().getAttribute(ConstConstants.EMPLOYEE_ID_IN_SESSION);
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }
        //移动端的登录验证
        if(request.getSession().getAttribute(ConstConstants.USER_ID_IN_SESSION)!=null){
            Long userId=(Long)request.getSession().getAttribute(ConstConstants.USER_ID_IN_SESSION);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

         response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }


    private boolean check(String requestURI){
        for (String url : ConstConstants.URLS) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
